package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.qo.EmployeeQueryObject;
import cn.wolfcode.crm.qo.JsonResult;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private RoleMapper roleMapper;

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageInfo<Role> pageResult = roleService.query(qo);
        model.addAttribute("result", pageResult);
        return "/role/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            roleMapper.deleteRelation(id);
            roleMapper.deleteERByRoleId(id);
            roleService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败");
        }
        return new JsonResult(true, "操作成功");
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //查询所有权限
        model.addAttribute("permissions", permissionService.listAll());

        if (id != null) {
            Role role = roleService.selectOne(id);
            model.addAttribute("role", role);
        }
        return "/role/input";
    }

    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() == null) {
            roleService.save(role, ids);

        } else {
            roleService.update(role, ids);
        }
        return "redirect:/role/list.do";
    }


}
